
import { Meta, Story, Canvas, ArgsTable } from '@storybook/addon-docs';
import store from '@/.storybook/store';
import detailPageAnchorNav from '../../../pages/detailPageAnchorNav.vue';

<Meta
  title="Pages/Detail Page Anchor Nav"
  component={detailPageAnchorNav}
  argTypes={{}}
/>

export const Template = (args, { argTypes }) => ({
  props: Object.keys(argTypes),
  components: { detailPageAnchorNav },
  store: store,
  template: '<detailPageAnchorNav />',
});

# Anchor navigation example

<a href="?path=/story/pages-detail-page-anchor-nav--example">Go to the Canvas Tab</a>

---

<a href="?id=pages-detail-page-anchor-nav--example&args=&viewMode=story" target="_blank">Open in full width in a new tab</a>

**Remarks:**
- the “sticky” functionality works only <a href="?id=pages-detail-page-anchor-nav--example&args=&viewMode=story" target="_blank">in full width view</a>
- A short Javascript example is displayed at the <a href="#javascript-example">bottom of the page</a>, showing how to set a class on the current menu item, depending on the scroll position.

<Canvas>
  <Story
    name="Example"
    args={{
      isOpen: false,
    }}
  >
    {Template.bind({})}
  </Story>
</Canvas>

# Javascript example

This is an example how to listen to the scroll and set an `.menu__item--active` class to the current menu item when a anchored section pops into the viewport.

```javascript
const AnchorNav = {
  setCurrentMenuItem() {
    // select all titles with an id in the main element.
    // this selection could be narrowed depending on the way the anchoring is implemented:
    const sections = document.querySelectorAll('main h2[id]');
    const scrollOffset = 100;
    // Listen to the scroll
    window.onscroll = () => {
      const scrollPos = document.documentElement.scrollTop || document.body.scrollTop;
      for (let s in sections) {
        // if a section pops in the viewport, the current active class is removed
        // and applied to this new appearing section:
        if (sections.hasOwnProperty(s) && sections[s].offsetTop <= scrollPos - scrollOffset) {
          const id = sections[s].id;
          let currentItem =  document.querySelector('.menu__item--active')
          if (currentItem) currentItem.classList.remove('menu__item--active');
          document.querySelector(`a[href*=${id}]`).classList.add('menu__item--active');
        }
      }
    }
  }
}
export default AnchorNav
```

Import the function above and init the script with

```javascript
AnchorNav.setCurrentMenuItem()
```
